package net.sf.midollo.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Echo extends MyHttpServlet {

  private static final long serialVersionUID = 1L;

  public static final int BUFFER_SIZE = 8 * 1024;
  protected final byte[] buffer = new byte[BUFFER_SIZE];

  protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    httpServletResponse.setContentType("text/plain");
  }

  protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    int contentLength = httpServletRequest.getContentLength();
    if (contentLength < 0)
      throw new IOException("Content-Length required");
    httpServletResponse.setContentType("text/plain");
    httpServletResponse.setContentLength(contentLength);
    ServletInputStream is = httpServletRequest.getInputStream();
    ServletOutputStream os = httpServletResponse.getOutputStream();
    int nread;
    int remain = contentLength;
    do {
      nread = is.read(this.buffer, 0, this.buffer.length);
      if (nread < 0)
        break;
      os.write(this.buffer, 0, nread);
      remain -= nread;
      if (remain <= 0)
        break;
    } while (true);
    os.flush();
  }
}
